package com.zhengyisky.controller;

import com.thoughtworks.xstream.XStream;
import com.zhengyisky.entity.WxTextMessage;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class WxController {

    @GetMapping("/wx")
    public String wxGet(String signature, String timestamp, String nonce,String echostr){
        System.out.println(signature);
        System.out.println(timestamp);
        System.out.println(nonce);
        System.out.println(echostr);
        return echostr;
    }

    @PostMapping("/wx")
    public String wxPost(HttpServletRequest request) throws Exception {
        ServletInputStream inputStream = request.getInputStream();
        SAXReader saxReader = new SAXReader();
        Document doc = saxReader.read(inputStream);
        Element root = doc.getRootElement();
        List<Element> elements = root.elements();

        Map<String,String> requestMap = new HashMap<>();
        for (Element child:elements) {
            requestMap.put(child.getName(),child.getStringValue());
        }

        //封装需要回复的XML报文
        WxTextMessage wxTextMessage = new WxTextMessage();
        wxTextMessage.setFromUserName(requestMap.get("ToUserName"));
        wxTextMessage.setToUserName(requestMap.get("FromUserName"));
        wxTextMessage.setContent("您的消息我们已收到:"+requestMap.get("Content"));
        wxTextMessage.setMsgType("text");
        wxTextMessage.setCreateTime(System.currentTimeMillis());

        XStream xStream = new XStream();
        xStream.alias("xml",WxTextMessage.class);
        String responseXML = xStream.toXML(wxTextMessage);
        return responseXML;
    }

}
